<?php
require_once('Smarty/libs/Smarty.class.php'); 

/**
 * konfiguracja, instalacja obiektów baz
 * wersji językowych
 * smarty
 *
 */
class SettingsController{
	public  function saveSettingsAction(){
		global $config;
		foreach ($config->cmssettings as $id => $wartosc) {
			$id__ = tools::__adodb('getOne',"SELECT id  FROM ".SETUP." WHERE id = ".tools::__mres($id)); 
			if($id == $id__){
				tools::__adodb("exec","UPDATE ".SETUP." SET wartosc = ".tools::__mres($wartosc)." WHERE id = ".tools::__mres($id));
			}else{
				tools::__adodb("exec","INSERT INTO ".SETUP." (id, wartosc) VALUES (".tools::__mres($id).",".tools::__mres($wartosc).");");
			}
		}
		tools::_redirect($config->page.".html",null,0,'php');
	}
}
/**
 * konfiguracja, instalacja obiektów baz
 * wersji językowych
 * smarty
 *
 */
class config extends Config_Http {
	public $debuging_query_data;
	public $cmsSettings;
	public $__cl;
	public $__lang;
	
	function __construct(){
		$this->debuging_query_data = '';
		
	}

	
	public function __set($__var, $__val){
		$this->$__var .= $__val;
	}

//	public function __get($__var){
//		return $this->$__var;
//	}
	
	public static function sprawdzTypDomeny($nowadomena){
		//if( MAIN_URL == HTTP_URL)
		$nowadomena = str_replace('www.','',str_replace('http://','',$nowadomena));
		$arr = unserialize(MAIN_URL);
		foreach ($arr as $domena ) {
			if ($nowadomena == $domena) return true;  
		}
		return false;		
	}
		
	/**
	 * debugging query exec
	 *
	 * @param String $__msg 
	 * @param Bollean $__newline
	 * @param String $__driver
	 */
	public static function debug_query($__msg,$__newline,$__driver,$time = 0){
		global $config;		
		if ($__newline) '<hr/>('.$__driver.') '.$__msg .= "<br/>\n";		
		if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) $config->debuging_query_data .=  "<hr/>(".$__driver.") [{$time}] ".$__msg;
		else $config->debuging_query_data .= strip_tags('<hr/>('.$__driver.') '.$__msg);
		if (ob_get_length() !== false) flush();		
		return strip_tags(date('Y.m.d H:i:s ').'('.$__driver.') '.$__msg);
	}
		
	/**
	 * sqlite database connection
	 *
	 * @param String $__user_host
	 * @return Object
	 */
	static function _get_pdo_obj_sqlite($__host=null,$my_driver = null){
		global $parameters;

		try { 
			$__drv = PDO::getAvailableDrivers();
			foreach ($__drv as $__driver){	if ( preg_match('/^sqlite.$/',$__driver) ) break;	}
			

			$drv = (is_null($my_driver))?$__driver:$my_driver;
			// baza uzytkownikow - polaczenie pozwala na usuwanie bazy z dysku			
			//$conn = new PDO("{$drv}:".$__host);
			
			// baza CMS - polaczenie cashowane przez PHP 
			$conn = new PDO("{$drv}:".$__host, null, null, array(PDO::ATTR_PERSISTENT => true));
			
			
			if( is_object($conn)){
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			
				// ustawienia
				$conn->query("PRAGMA short_column_names = 1;");
				
			
			return $conn;
			}else{
				//echo "<span class=\"red\">Brak połączenia z bazą. {$__host}</span>";
				return false;
			}
		} catch (exception $e) {
			 echo "Brak połączenia z bazą: " . $e->getMessage() . "\n";	
		} 
	}
	
	static function _get_pdo_obj_mysql ($host,$database,$username,$password, $port){
		global $parameters;
		try { 
			$db = new PDO("mysql:host=$host;dbname=$database;port={$port}", $username, $password);
	        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			return $db;
        } catch (exception $e) {
			 echo "Brak połączenia z bazą: " . $e->getMessage() . "\n";	
		} 
	}
	
	public function themeSettings(){	
		if (is_array($this->cmsSettings)){
			// domyslny szabon
			if (!isset($this->cmsSettings['szablon'])) $this->cmsSettings['szablon'] = '0000';
			if (!isset($this->cmsSettings['css'])) $this->cmsSettings['css'] = '0000/ramki/000_000000/0000_000_0000000.css';
			return $this->cmsSettings;
		}else{
			return array('szablon'=>'0000','css'=>'0000/ramki/000_000000/0000_000_000000.css');
		}
	}
	

	
	/**
	 * Smarty connection
	 *
	 * @return Object
	 */
	static function _get_smarty_obj(){
		global $dispatcher,$exten_dispatcher, $parameters;
		$smarty = new Smarty;										 
		$smarty->template_dir = array($parameters['smarty']['template_dir'],$parameters['smarty']['template_skins_dir'],$parameters['smarty']['template_theme_dir']);
		$smarty->compile_dir = $parameters['smarty']['compile_dir'];
		$smarty->cache_dir = $parameters['smarty']['cache_dir'];
		$smarty->config_dir = $parameters['smarty']['config_dir'];
		$smarty->compile_check = true;
		$smarty->debugging = $parameters['smarty']['debugging'];
		$smarty->plugins_dir = array(
					'../library/Smarty/libs/plugins', // the default under SMARTY_DIR
					'../../SmartyPlugins'
				);
		
		$smarty->register_modifier('strsla', 'stripslashes');
		$smarty->register_function('basename', 'basename');
		$smarty->register_modifier('unserial', 'unserialize');
		$smarty->register_object('dispatcher',$dispatcher,null,false);
		$smarty->register_object('exten',$exten_dispatcher,null,false);
		$smarty->register_resource('smarty_db', array(
			'recompile_get_template',
			'recompile_get_timestamp',
			'recompile_get_secure',
			'recompile_get_trusted')
		);
	
		return $smarty;
	}
	
	/**
	 * Default or selected language instalatiin
	 *
	 */
	public function _get_language(){
		global $config,$parameters,$objSession;
		$this->__lang = $objSession->userLanguage;
		$instaledLanguage = unserialize(LANGU);
		if(isset($this->cmsSettings['defaultLanguage'])) $defaultLanguage = (isset($instaledLanguage[$this->cmsSettings['defaultLanguage']])) ? $this->cmsSettings['defaultLanguage'] : $parameters['info']['language'];
		else $defaultLanguage = $parameters['info']['language'];
		$this->__lang = /*$objSession->userLanguage = */ ( $this->__lang != false ) ? $this->__lang : $defaultLanguage;
		tools::_assign('defaultLanguage',$defaultLanguage);

		if (is_file("../lang/{$this->__lang}.lang")){
			$__constants_language = parse_ini_file("../lang/{$this->__lang}.lang");
		}
		$this->__cl = (isset($__constants_language)) ? $__constants_language : array();
		
		tools::_assign('__cl',$this->__cl);
	}
	

	/**
	 * get site configuration form ini file
	 *
	 * @return Array
	 */
	static function _instal_ini(){
		$__c = parse_ini_file('../ini/config.ini',true);	
		return $__c;
	}
	
	
	static function getDB($parameters){
		switch($parameters['drivers']['driver']){
			case 'sqlite':
				// baza cms na sqlite
				$dbl = config::_get_pdo_obj_sqlite($parameters['sqlite']['host'].$parameters['sqlite']['database']);
				break;
			case 'sqlite3':
				// baza cms na sqlite
				$dbl = config::_get_pdo_obj_sqlite($parameters['sqlite']['host'].$parameters['sqlite']['database'],"sqlite");
				break;
			case 'mysql':	
				// baza cms na mysql
				$dbl = config::_get_pdo_obj_mysql($parameters['mysql']['host'],$parameters['mysql']['database'],$parameters['mysql']['login'],$parameters['mysql']['pass'],$parameters['mysql']['port']);
		
				tools::__adodb('exec','SET CHARACTER SET utf8;');
				tools::__adodb('exec','SET NAMES utf8;');
				break;
		}	
		return $dbl;
	}
	
	
	/**
	 * install main database
	 *
	 */
	static function _instal_database($driver="sqlite",$dbx=null){

		switch($driver){
			case 'sqlite':
				$__arr = tools::__adodb('getAll',"SELECT name FROM sqlite_master WHERE type='table'",true,$dbx,$driver);
				break;
			case 'mysql':
				$__arr = tools::__adodb('getAll',"show tables");
				break;
		}
			
		$__tabels = tools::__count_row($__arr);
		
		if ( $__tabels == 0 ) {
			include_once 'Panel/InstallDatabase.php';
			$isnt = new InstallDatabaseController();
			$isnt->indexAction($dbx);
		}	
	}

	
	public static function _fetch_section_form_db($__section){
		global $smarty;
		$smarty->clear_compiled_tpl("smarty_db:".$__section);
		return $smarty->fetch("smarty_db:".$__section);
	}
	

}


/*********************** RESOURCES *********************/
				
function recompile_get_template ($tpl_name, &$tpl_source, &$smarty){	
	global $objSession;
		
	$__section_info = explode(",",$tpl_name);
	$__q_get_section_body = "SELECT section_body,section_body_hidden, section_body_sometime, exten_body FROM ".THEME." 
		WHERE id_page = ".tools::__mres($__section_info[0])." AND id_section = ".tools::__mres($__section_info[1])."
		AND id_lang = ".tools::__mres($__section_info[2]);
	$__section_body__ = tools::__adodb("getRow",$__q_get_section_body);
	$__section_body = tools::stripslashes_array($__section_body__);
	$__section_body_hiden = ( $objSession->IsLoggedIn()) ? $__section_body['section_body_hidden'] : '';
	$__section_body_sometime = ( !$objSession->IsLoggedIn()) ? $__section_body['section_body_sometime'] : '';
	$tpl_source = ( $__section_body != false ) ? $__section_body['section_body'].$__section_body_sometime.$__section_body_hiden.$__section_body['exten_body'] : "brak danych...";
	return true;
}
function recompile_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty){
	$__section_info = explode(",",$tpl_name);
	$__q_get_last_modification = "SELECT last_modification FROM ".THEME." 
		WHERE id_page = ".tools::__mres($__section_info[0])." AND id_section = ".tools::__mres($__section_info[1])."
		AND id_lang = ".tools::__mres($__section_info[2]);
	$__last_modification = tools::__adodb("getOne",$__q_get_last_modification);
	$tpl_timestamp = ( $__last_modification != false ) ? stripslashes($__last_modification) : "brak danych...";
	return true;

}
function recompile_get_secure($tpl_name, &$smarty_obj)
{
// assume all templates are secure
return true;
}
function recompile_get_trusted($tpl_name, &$smarty_obj)
{
// not used for templates
}